package com.smart.community.region.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smart.community.region.entity.Building;
import com.smart.community.region.entity.Household;
import com.smart.community.region.entity.Unit;
import com.smart.community.region.mapper.BuildingMapper;
import com.smart.community.region.mapper.HouseholdMapper;
import com.smart.community.region.mapper.UnitMapper;
import com.smart.community.region.service.IDataImportService;
import com.smart.community.region.utils.DataValidationUtils;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

/**
 * 数据导入服务实现类
 * 
 * @author Wu.Liang
 * @since 2025-01-30
 */
@Slf4j
@Service
public class DataImportServiceImpl implements IDataImportService {

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private UnitMapper unitMapper;

    @Autowired
    private HouseholdMapper householdMapper;

    @Autowired
    private DataValidationUtils dataValidationUtils;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ImportResult importCommunityData(Map<String, List<Map<String, Object>>> data, Long communityId, Long userId) {
        ImportResult result = new ImportResult();
        
        try {
            List<Map<String, Object>> buildings = data.get("buildings");
            List<Map<String, Object>> units = data.get("units");
            List<Map<String, Object>> households = data.get("households");
            
            // 数据验证
            DataValidationUtils.ValidationResult buildingValidation = dataValidationUtils.validateBuildingData(buildings, communityId);
            DataValidationUtils.ValidationResult unitValidation = dataValidationUtils.validateUnitData(units, buildings, communityId);
            DataValidationUtils.ValidationResult householdValidation = dataValidationUtils.validateHouseholdData(households, buildings, units, communityId);
            
            // 检查验证结果
            if (buildingValidation.hasErrors() || unitValidation.hasErrors() || householdValidation.hasErrors()) {
                result.setSuccess(false);
                result.setMessage("数据验证失败，请检查错误信息");
                result.setBuildingErrors(buildingValidation.getErrors());
                result.setUnitErrors(unitValidation.getErrors());
                result.setHouseholdErrors(householdValidation.getErrors());
                return result;
            }
            
            // 检查数据库中是否已存在数据
            if (hasExistingData(communityId)) {
                result.setSuccess(false);
                result.setMessage("该社区已存在楼栋、单元或房户数据，请先清空现有数据");
                return result;
            }
            
            // 批量导入楼栋数据
            List<Building> buildingEntities = importBuildings(buildings, communityId, userId);
            result.setBuildingCount(buildingEntities.size());
            
            // 批量导入单元数据
            List<Unit> unitEntities = importUnits(units, buildingEntities, communityId, userId);
            result.setUnitCount(unitEntities.size());
            
            // 批量导入房户数据
            List<Household> householdEntities = importHouseholds(households, buildingEntities, unitEntities, communityId, userId);
            result.setHouseholdCount(householdEntities.size());
            
            result.setSuccess(true);
            result.setMessage("数据导入成功");
            
            log.info("社区数据导入成功，社区ID：{}，楼栋：{}个，单元：{}个，房户：{}个", 
                    communityId, buildingEntities.size(), unitEntities.size(), householdEntities.size());
            
        } catch (Exception e) {
            log.error("社区数据导入失败，社区ID：{}", communityId, e);
            result.setSuccess(false);
            result.setMessage("数据导入失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 检查是否存在现有数据
     */
    private boolean hasExistingData(Long communityId) {
        // 检查楼栋数据
        long buildingCount = buildingMapper.countBuildings(communityId);
        if (buildingCount > 0) {
            return true;
        }
        
        // 检查单元数据
        long unitCount = unitMapper.countUnits(communityId);
        if (unitCount > 0) {
            return true;
        }
        
        // 检查房户数据
        long householdCount = householdMapper.countByCommunityId(communityId);
        return householdCount > 0;
    }

    /**
     * 导入楼栋数据
     */
    private List<Building> importBuildings(List<Map<String, Object>> buildings, Long communityId, Long userId) {
        List<Building> buildingEntities = new ArrayList<>();
        
        for (Map<String, Object> buildingData : buildings) {
            Building building = new Building();
            building.setCommunityId(communityId);
            building.setBuildingNo((String) buildingData.get("buildingNo"));
            building.setBuildingName((String) buildingData.get("buildingName"));
            building.setFloorCount(Integer.parseInt(buildingData.get("floorCount").toString()));
            building.setUnitCount(Integer.parseInt(buildingData.get("unitCount").toString()));
            building.setUnitsPerFloor(Integer.parseInt(buildingData.get("unitsPerFloor").toString()));
            
            // 可选字段
            if (buildingData.get("buildingType") != null) {
                // 楼栋类型：1-住宅楼，2-商业楼，3-办公楼，4-综合楼
                String buildingTypeStr = (String) buildingData.get("buildingType");
                building.setBuildingType(buildingTypeStr);
//                if ("住宅楼".equals(buildingTypeStr)) {
//                    building.setBuildingType(1);
//                } else if ("商业楼".equals(buildingTypeStr)) {
//                    building.setBuildingType(2);
//                } else if ("办公楼".equals(buildingTypeStr)) {
//                    building.setBuildingType(3);
//                } else if ("综合楼".equals(buildingTypeStr)) {
//                    building.setBuildingType(4);
//                } else {
//                    building.setBuildingType(1); // 默认住宅楼
//                }
            }
            if (buildingData.get("buildYear") != null) {
                building.setBuildYear(Integer.parseInt(buildingData.get("buildYear").toString()));
            }
            if (buildingData.get("remark") != null) {
                building.setRemark((String) buildingData.get("remark"));
            }
            
            // 设置默认值
            building.setStatus(1); // 1-启用
            building.setCreateTime(LocalDateTime.now());
            building.setCreateBy(userId);
            building.setUpdateTime(LocalDateTime.now());
            building.setUpdateBy(userId);
            
            buildingEntities.add(building);
        }
        
        // 批量插入楼栋数据
        if (!buildingEntities.isEmpty()) {
            try {
                // 检查数据冲突
                List<String> buildingNos = buildingEntities.stream()
                        .map(Building::getBuildingNo)
                        .collect(Collectors.toList());
                
                // 查询数据库中是否已存在相同的楼栋编号
                List<Building> existingBuildings = buildingMapper.selectByBuildingNosAndCommunityId(buildingNos, communityId);
                if (!existingBuildings.isEmpty()) {
                    List<String> conflictNos = existingBuildings.stream()
                            .map(Building::getBuildingNo)
                            .collect(Collectors.toList());
                    throw new RuntimeException("楼栋编号已存在：" + String.join(", ", conflictNos));
                }
                
                // 批量插入
                buildingMapper.batchInsert(buildingEntities);
                log.info("批量插入楼栋数据成功，数量：{}", buildingEntities.size());
            } catch (Exception e) {
                log.error("批量插入楼栋数据失败", e);
                throw new RuntimeException("楼栋数据导入失败：" + e.getMessage());
            }
        }
        
        return buildingEntities;
    }

    /**
     * 导入单元数据
     */
    private List<Unit> importUnits(List<Map<String, Object>> units, List<Building> buildings, Long communityId, Long userId) {
        List<Unit> unitEntities = new ArrayList<>();
        
        // 构建楼栋映射
        Map<String, Building> buildingMap = buildings.stream()
                .collect(Collectors.toMap(Building::getBuildingNo, building -> building));
        
        for (Map<String, Object> unitData : units) {
            String buildingNo = (String) unitData.get("buildingNo");
            Building building = buildingMap.get(buildingNo);
            
            Unit unit = new Unit();
            unit.setCommunityId(communityId);
            unit.setBuildingId(building.getId());
            unit.setUnitNo(String.valueOf(unitData.get("unitNo")));
            unit.setUnitName((String) unitData.get("unitName"));
            unit.setFloorCount(Integer.parseInt(unitData.get("floorCount").toString()));
            unit.setRoomCount(Integer.parseInt(unitData.get("roomCount").toString()));
            
            // 可选字段
            if (unitData.get("householdCount") != null) {
                unit.setHouseholdCount(Integer.parseInt(unitData.get("householdCount").toString()));
            } else {
                unit.setHouseholdCount(0);
            }
            
            if (unitData.get("hasElevator") != null) {
                String hasElevator = (String) unitData.get("hasElevator");
                unit.setHasElevator("是".equals(hasElevator) ? 1 : 0);
            }
            
            if (unitData.get("elevatorCount") != null) {
                unit.setElevatorCount(Integer.parseInt(unitData.get("elevatorCount").toString()));
            }
            
            if (unitData.get("doorAccessType") != null) {
                // 门禁类型：1-密码，2-刷卡，3-人脸识别，4-指纹
                String doorAccessTypeStr = (String) unitData.get("doorAccessType");
                if ("密码".equals(doorAccessTypeStr)) {
                    unit.setDoorAccessType(1);
                } else if ("刷卡".equals(doorAccessTypeStr)) {
                    unit.setDoorAccessType(2);
                } else if ("人脸识别".equals(doorAccessTypeStr)) {
                    unit.setDoorAccessType(3);
                } else if ("指纹".equals(doorAccessTypeStr)) {
                    unit.setDoorAccessType(4);
                } else {
                    unit.setDoorAccessType(1); // 默认密码
                }
            }
            
            if (unitData.get("status") != null) {
                // 状态：0-建设中，1-正常使用，2-维修中，3-停用
                String statusStr = (String) unitData.get("status");
                if ("启用".equals(statusStr) || "正常使用".equals(statusStr)) {
                    unit.setStatus(1);
                } else if ("建设中".equals(statusStr)) {
                    unit.setStatus(0);
                } else if ("维修中".equals(statusStr)) {
                    unit.setStatus(2);
                } else if ("停用".equals(statusStr)) {
                    unit.setStatus(3);
                } else {
                    unit.setStatus(1); // 默认正常使用
                }
            } else {
                unit.setStatus(1); // 默认正常使用
            }
            
            if (unitData.get("remark") != null) {
                unit.setRemark((String) unitData.get("remark"));
            }
            
            // 设置默认值
            unit.setCreateTime(LocalDateTime.now());
            unit.setCreateBy(userId);
            unit.setUpdateTime(LocalDateTime.now());
            unit.setUpdateBy(userId);
            
            unitEntities.add(unit);
        }
        
        // 批量插入单元数据
        if (!unitEntities.isEmpty()) {
            try {
                unitMapper.batchInsert(unitEntities);
                log.info("批量插入单元数据成功，数量：{}", unitEntities.size());
            } catch (Exception e) {
                log.error("批量插入单元数据失败", e);
                throw new RuntimeException("单元数据导入失败：" + e.getMessage());
            }
        }
        
        return unitEntities;
    }

    /**
     * 导入房户数据
     */
    private List<Household> importHouseholds(List<Map<String, Object>> households, 
                                           List<Building> buildings, 
                                           List<Unit> units, 
                                           Long communityId, 
                                           Long userId) {
        List<Household> householdEntities = new ArrayList<>();
        
        // 构建楼栋和单元映射
        Map<String, Building> buildingMap = buildings.stream()
                .collect(Collectors.toMap(Building::getBuildingNo, building -> building));
        
        Map<String, Unit> unitMap = new HashMap<>();
        for (Unit unit : units) {
            Building building = buildingMap.get(unit.getBuildingId());
            if (building != null) {
                unitMap.put(building.getBuildingNo() + "-" + unit.getUnitNo(), unit);
            }
        }
        
        for (Map<String, Object> householdData : households) {
            String buildingNo = (String) householdData.get("buildingNo");
            int unitNo = Integer.parseInt(householdData.get("unitNo").toString());
            String unitKey = buildingNo + "-" + unitNo;
            
            Building building = buildingMap.get(buildingNo);
            Unit unit = unitMap.get(unitKey);
            
            Household household = new Household();
            household.setCommunityId(communityId);
            household.setBuildingId(building.getId());
            household.setUnitId(unit.getId());
            household.setHouseholdCode((String) householdData.get("householdCode"));
            household.setRoomNumber((String) householdData.get("roomNumber"));
            household.setFloorNumber(Integer.parseInt(householdData.get("floorNumber").toString()));
            household.setArea(BigDecimal.valueOf(Double.parseDouble(householdData.get("area").toString())));
            
            // 可选字段
            if (householdData.get("houseType") != null) {
                // 房间类型：1-一室，2-两室，3-三室，4-四室及以上
                String houseTypeStr = (String) householdData.get("houseType");
                if ("一室".equals(houseTypeStr)) {
                    household.setRoomType(1);
                } else if ("两室".equals(houseTypeStr)) {
                    household.setRoomType(2);
                } else if ("三室".equals(houseTypeStr)) {
                    household.setRoomType(3);
                } else if ("四室及以上".equals(houseTypeStr)) {
                    household.setRoomType(4);
                } else {
                    household.setRoomType(2); // 默认两室
                }
            }
            
            if (householdData.get("orientation") != null) {
                household.setOrientation((String) householdData.get("orientation"));
            }
            
            if (householdData.get("decorationStatus") != null) {
                // 装修状态：0-毛坯，1-简装，2-精装，3-豪装
                String decorationStatusStr = (String) householdData.get("decorationStatus");
                if ("毛坯".equals(decorationStatusStr)) {
                    household.setStatus(0);
                } else if ("简装".equals(decorationStatusStr)) {
                    household.setStatus(1);
                } else if ("精装".equals(decorationStatusStr)) {
                    household.setStatus(2);
                } else if ("豪装".equals(decorationStatusStr)) {
                    household.setStatus(3);
                } else {
                    household.setStatus(1); // 默认简装
                }
            }
            
            if (householdData.get("status") != null) {
                // 状态：0-空置，1-已入住，2-装修中，3-出租
                String statusStr = (String) householdData.get("status");
                if ("空置".equals(statusStr)) {
                    household.setStatus(0);
                } else if ("已入住".equals(statusStr)) {
                    household.setStatus(1);
                } else if ("装修中".equals(statusStr)) {
                    household.setStatus(2);
                } else if ("出租".equals(statusStr)) {
                    household.setStatus(3);
                } else {
                    household.setStatus(0); // 默认空置
                }
            } else {
                household.setStatus(0); // 默认空置
            }
            
            if (householdData.get("remark") != null) {
                household.setDescription((String) householdData.get("remark"));
            }
            
            // 设置默认值
            household.setCreateTime(LocalDateTime.now());
            household.setCreateBy(userId);
            household.setUpdateTime(LocalDateTime.now());
            household.setUpdateBy(userId);
            
            householdEntities.add(household);
        }
        
        // 批量插入房户数据
        if (!householdEntities.isEmpty()) {
            try {
                householdMapper.batchInsert(householdEntities);
                log.info("批量插入房户数据成功，数量：{}", householdEntities.size());
            } catch (Exception e) {
                log.error("批量插入房户数据失败", e);
                throw new RuntimeException("房户数据导入失败：" + e.getMessage());
            }
        }
        
        return householdEntities;
    }

    /**
     * 导入结果类
     */
    public static class ImportResult {
        private boolean success;
        private String message;
        private int buildingCount;
        private int unitCount;
        private int householdCount;
        private List<DataValidationUtils.ValidationError> buildingErrors;
        private List<DataValidationUtils.ValidationError> unitErrors;
        private List<DataValidationUtils.ValidationError> householdErrors;
        
        // Getters and Setters
        public boolean isSuccess() {
            return success;
        }
        
        public void setSuccess(boolean success) {
            this.success = success;
        }
        
        public String getMessage() {
            return message;
        }
        
        public void setMessage(String message) {
            this.message = message;
        }
        
        public int getBuildingCount() {
            return buildingCount;
        }
        
        public void setBuildingCount(int buildingCount) {
            this.buildingCount = buildingCount;
        }
        
        public int getUnitCount() {
            return unitCount;
        }
        
        public void setUnitCount(int unitCount) {
            this.unitCount = unitCount;
        }
        
        public int getHouseholdCount() {
            return householdCount;
        }
        
        public void setHouseholdCount(int householdCount) {
            this.householdCount = householdCount;
        }
        
        public List<DataValidationUtils.ValidationError> getBuildingErrors() {
            return buildingErrors;
        }
        
        public void setBuildingErrors(List<DataValidationUtils.ValidationError> buildingErrors) {
            this.buildingErrors = buildingErrors;
        }
        
        public List<DataValidationUtils.ValidationError> getUnitErrors() {
            return unitErrors;
        }
        
        public void setUnitErrors(List<DataValidationUtils.ValidationError> unitErrors) {
            this.unitErrors = unitErrors;
        }
        
        public List<DataValidationUtils.ValidationError> getHouseholdErrors() {
            return householdErrors;
        }
        
        public void setHouseholdErrors(List<DataValidationUtils.ValidationError> householdErrors) {
            this.householdErrors = householdErrors;
        }
    }
}
